<template>
  <div class="dailyTrainCarriage">
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
      class="layout-content"
    >
      <a-space>
        <date-time-select v-model="search.date"></date-time-select>
        <train-code-input v-model="search.code"></train-code-input>
        <a-button type="primary" @click="flush"> 查找 </a-button>
        <a-button type="primary" @click="openAdd"> 新增 </a-button>
      </a-space>

      <!-- 新增每日车厢模态窗口 -->
      <a-modal
        v-model="visible"
        :title="isEdit ? '编辑每日车厢' : '新增每日车厢'"
        @ok="handleOk"
        cancelText="取消"
        okText="确认"
        :closable="closable"
        @cancel="handleCancel"
      >
        <a-form
          :form="form"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-form-item label="id" hidden>
            <a-input v-decorator="['id']" />
          </a-form-item>
          <a-form-item label="日期">
            <a-config-provider :locale="locale">
              <a-date-picker
                v-decorator="[
                  'date',
                  { rules: [{ required: true, message: '请选择日期!' }] },
                ]"
                show-time
                format="YYYY-MM-DD"
                placeholder="请选择日期"
                :showToday="showToday"
                mode="date"
                valueFormat="YYYY-MM-DD"
              />
            </a-config-provider>
          </a-form-item>
          <a-form-item label="车次编号">
            <a-input
              v-decorator="[
                'trainCode',
                {
                  rules: [{ required: true, message: '请输入车次编号!' }],
                },
              ]"
              placeholder="请输入车次编号"
              :disabled="isEdit"
              @input="inputQueryCondition"
            />
          </a-form-item>
          <a-form-item label="箱序">
            <a-input
              v-decorator="[
                'index',
                {
                  rules: [{ required: true, message: '请输入箱序!' }],
                },
              ]"
              @input="inputQueryCondition"
            />
          </a-form-item>
          <a-form-item label="座位类型">
            <a-select
              v-decorator="[
                'seatType',
                {
                  rules: [{ required: true, message: '请选择座位类型!' }],
                },
              ]"
              placeholder="请选择座位类型"
            >
              <a-select-option v-for="item in seatTypeItems" :key="item.code">
                {{ item.message }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="排数">
            <a-input
              v-decorator="[
                'rowCount',
                {
                  rules: [{ required: true, message: '请输入排数!' }],
                },
              ]"
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 列表 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :rowKey="
          (record, index) => {
            return index;
          }
        "
        :scroll="{ x: 1080, y: 400 }"
        :pagination="pagination"
        @change="handlePage"
        :loading="loading"
      >
        <span slot="action" slot-scope="record">
          <a @click="openEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleRemove(record.id)">删除</a>
        </span>
      </a-table>
    </a-layout-content>
  </div>
</template>

<script>
import { add, getPage, edit, remove } from "@/api/dailyTrainCarriage";
import { notification, Modal } from "ant-design-vue";
import "ant-design-vue/lib/notification/style/css";
import zhCN from "ant-design-vue/es/locale/zh_CN";
import TrainCodeInput from "@/components/TrainCodeInput.vue";
import DateTimeSelect from "@/components/DateTimeSelect.vue";
import { getTrainCarriage } from "@/api/trainCarriage";

export default {
  name: "dailyTrainCarriage",
  components: { TrainCodeInput, DateTimeSelect },
  data() {
    return {
      visible: false,
      form: this.$form.createForm(this, { name: "coordinated" }),
      scrollY: 400,
      loading: false,
      closable: false,
      isEdit: false,
      code: "",
      description: "",
      locale: zhCN,
      seatTypeItems: window.SEAT_TYPE_ARRAY,
      showToday: true,
      pagination: {
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"],
        showTotal: (total, range) =>
          "显示" +
          range[0] +
          " ~ " +
          range[1] +
          "条记录，共" +
          total +
          "条记录",
        pageSize: 10,
        current: 1,
        total: 0,
      },
      columns: [
        {
          title: "日期",
          dataIndex: "date",
          key: "date",
          align: "center",
          width: 150,
        },
        {
          title: "车次编号",
          dataIndex: "trainCode",
          key: "trainCode",
          align: "center",
          width: 150,
        },
        {
          title: "箱序",
          dataIndex: "index",
          key: "index",
          align: "center",
          width: 150,
        },
        {
          title: "座位类型",
          dataIndex: "seatType",
          key: "seatType",
          align: "center",
          width: 150,
          customRender: (text, record, index) => {
            const seatTypeItem = this.seatTypeItems.find(
              (item) => item.code === text
            );
            return seatTypeItem ? seatTypeItem.message : text;
          },
        },
        {
          title: "座位数",
          dataIndex: "seatCount",
          key: "seatCount",
          align: "center",
          width: 150,
        },
        {
          title: "排数",
          dataIndex: "rowCount",
          key: "rowCount",
          align: "center",
          width: 150,
        },
        {
          title: "列数",
          dataIndex: "colCount",
          key: "colCount",
          align: "center",
          width: 150,
        },
        {
          title: "新增时间",
          dataIndex: "createTime",
          key: "createTime",
          align: "center",
          width: 150,
        },
        {
          title: "修改时间",
          dataIndex: "updateTime",
          key: "updateTime",
          align: "center",
          width: 150,
        },
        {
          title: "操作",
          key: "operation",
          fixed: "right",
          width: 110,
          scopedSlots: { customRender: "action" },
        },
      ],
      data: [],
      queryCondition: {
        trainCode: "",
        index: "",
      },
      search: {
        code: "",
        date: "",
      },
    };
  },
  watch: {
    queryCondition: {
      deep: true,
      handler(newValue, oldValue) {
        console.log(newValue);
        if (
          newValue.trainCode !== "" &&
          newValue.trainCode !== undefined &&
          newValue.index !== "" &&
          newValue.index !== undefined
        ) {
          //根据车次获取车次详情
          getTrainCarriage(newValue).then((res) => {
            if (res.code === 200) {
              const resp = res.data;
              this.form.setFieldsValue({
                seatType: resp ? resp.seatType : "",
                rowCount: resp ? resp.rowCount : "",
              });
            }
          });
        }
      },
    },
  },

  mounted() {
    this.handlePage();
  },
  methods: {
    inputQueryCondition() {
      this.queryCondition.trainCode = this.form.getFieldValue("trainCode");
      this.queryCondition.index = this.form.getFieldValue("index");
    },
    handleOk(e) {
      this.form.validateFields((err, values) => {
        if (err) {
          return;
        } else {
          this.handleAddOrEdit(values);
        }
      });
    },
    async handleAddOrEdit(values) {
      if (this.isEdit) {
        //发起更新请求
        await edit(values).then((res) => {
          this.description = "每日车厢更新成功";
          this.code = res.code;
        });
      } else {
        //发起新增请求
        await add(values).then((res) => {
          this.description = "每日车厢添加成功";
          this.code = res.code;
        });
      }
      if (this.code === 200) {
        notification.success({
          message: "消息提示",
          description: this.description,
          duration: 2,
        });
        //关闭表单
        this.visible = false;
        //清空表单
        this.form.resetFields();

        //刷新表格
        this.handlePage({
          current: this.pagination.current,
          pageSize: this.pagination.pageSize,
        });
      }
    },
    handleCancel(e) {
      this.form.resetFields();
    },
    flush() {
      this.handlePage();
    },
    handlePage(pagination, filters, sorter) {
      this.loading = true;
      const pageNo = pagination === undefined ? 1 : pagination.current;
      const pageSize = pagination === undefined ? 10 : pagination.pageSize;
      getPage(pageNo, pageSize, this.search).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          //设置每页码和每页显示数
          this.pagination.current = pageNo;
          this.pagination.pageSize = pageSize;
          //获取结果
          const dailyTrainCarriageList = res.data.data;
          this.data = dailyTrainCarriageList;
          this.pagination.total = res.data.total;
        } else {
          notification.error({
            message: "消息提示",
            description: res.message,
            duration: 3,
          });
        }
      });
    },
    openEdit(record) {
      this.isEdit = true;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          id: record.id,
          date: record.date,
          trainCode: record.trainCode,
          index: record.index,
          seatType: record.seatType,
          rowCount: record.rowCount,
        });
      });
      this.visible = true;
    },
    openAdd() {
      this.isEdit = false;
      this.visible = true;
    },
    handleRemove(id) {
      Modal.confirm({
        title: "是否确认删除?",
        okText: "是",
        okType: "danger",
        cancelText: "否",
        centered: true,
        onOk: () => {
          remove(id).then((res) => {
            if (res.code === 200) {
              notification.success({
                message: "消息提示",
                description: "每日车厢删除成功",
                duration: 2,
              });
              this.handlePage({
                current: this.pagination.current,
                pageSize: this.pagination.pageSize,
              });
            } else {
              notification.error({
                message: "消息提示",
                description: res.message,
                duration: 2,
              });
            }
          });
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.ant-input {
  width: 300px;
}
.ant-table-wrapper {
  margin-top: 20px;
}
/deep/ .ant-table-header {
  padding-bottom: 0 !important;
}
/deep/ .ant-select-selection--single {
  width: 195px !important;
}
/deep/ .ant-table-thead > tr > th {
  border-bottom: 0 !important;
}
</style>
